package com.taotao.service.impl;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.taotao.common.utils.*;
import com.taotao.mapper.*;
import com.taotao.pojo.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.taotao.common.enums.OperateType;
import com.taotao.common.enums.TemplateDesc;
import com.taotao.common.pojo.BaseResult;
import com.taotao.common.pojo.WxMssVo;
import com.taotao.service.CommonService;
import com.taotao.service.MessageInfoService;
import com.taotao.service.OperateLogService;
import com.taotao.service.ParamService;
import com.taotao.service.RemindLogService;
import com.taotao.service.WechatService;
import com.taotao.trans.CommonUtil;

@Service
public class WechatServiceImpl implements WechatService {

	private static final Logger logger = LoggerFactory.getLogger(WechatServiceImpl.class);

	@Autowired
	TbDeptMapper tbDeptMapper;
	@Autowired
	MessageInfoService messageInfoService;
	@Autowired
	ParamService paramService;
	@Autowired
	CommonService commonService;
	@Autowired
	EyMemberMapper eyMemberMapper;
	@Autowired
	EyOfficialAccountsMapper eyOfficialAccountsMapper;
	@Autowired
	OperateLogService operateLogService;
	@Autowired
	RemindLogService remindLogService;
	@Autowired
	EyGoodsMapper eyGoodsMapper;
	@Autowired
	EyOrderMapper eyOrderMapper;

	public static String accessToken_xcx_prefix = "accessToken_xcx";
	public static String accessToken_gzh_prefix = "accessToken_gzh";
	public static String ticket = "ticket";
	public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	  
	
	BaseResult baseResult = new BaseResult();

	public static void main(String[] args) {
		HashMap<String, String> map = new HashMap<String, String>();
		String appId = "wxf6c50dddc7929eef";
		String appSecret = "d6cbbf11df376445f02c6c94177a4911";
		
		
//		String jsonObject="{\"openid\":\"o6CkI04GurfQQc3_3QvHmTagqLNA\",\"subscribe\":0,\"tagid_list\":[]}";
//		JSONObject jsonObject2 =JSONObject.parseObject(jsonObject);
//		EyOfficialAccounts account=new EyOfficialAccounts();
//		
//		WechatServiceImpl wechat=new WechatServiceImpl();
//		wechat.initOfficialAccounts(jsonObject2,account);

		//通过静默授权获取用户的code 通过code码来获取公众号的openid 从而给用户推送消息
		String code = "061nJe3v1F8MHh0mVC5v1SBp3v1nJe38";  
		String grantType = "authorization_code";
		String params = "appid=" + appId + "&secret=" + appSecret + "&code=" + code + "&grant_type=" + grantType;
		String access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token";
		map.put("params", params);
		map.put("url", access_token_url);
		WechatServiceImpl wechat = new WechatServiceImpl();
		Map<String, Object> returnMap = wechat.sendGet(map);
		if ("000000".equals(returnMap.get("resultCode"))) {
			JSONObject object = (JSONObject) returnMap.get("data");
			System.out.println("data--->:" + object);
			String openid = String.valueOf(object.get("openid"));
			String access_token = String.valueOf(object.get("access_token"));
			System.out.println("openId-->" + openid);
			System.out.println("access_token-->" + access_token);
//			wechat.sendMsg(openid, access_token);
		}
	}
	
	@Override
	public void getAuthInfo(HttpServletRequest request) {
		 String code=request.getParameter("code");//公众号授权code
		 String unionid=request.getParameter("unionid");//公众号授权code
		 
		 EyMemberExample exampleMember = new EyMemberExample();
		 com.taotao.pojo.EyMemberExample.Criteria criteriaMember = exampleMember.createCriteria();
		 criteriaMember.andUnionIdEqualTo(unionid);
		 List<EyMember> listMember = eyMemberMapper.selectByExample(exampleMember);
		 EyMember member = null;
		 if(listMember!=null && listMember.size()>0){
			member = listMember.get(0);
			operateLogService.insert(member.getId(), null,null,OperateType.operateType_26.getDesc(),OperateType.operateType_26.getCode(),""); 
		 }
		 
		 String appId=paramService.getParam("appId_gzh");
         String appSecret=paramService.getParam("appSecret_gzh");
		 String grantType = "authorization_code";
		 String params = "appid=" + appId + "&secret=" + appSecret + "&code=" + code + "&grant_type=" + grantType;
		 String access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token";
		 HashMap<String, String> map = new HashMap<String, String>();
		 map.put("params", params);
		 map.put("url", access_token_url);
		 WechatServiceImpl wechat = new WechatServiceImpl();
		 Map<String, Object> returnMap = wechat.sendGet(map);
		 if ("000000".equals(returnMap.get("resultCode"))) {
			JSONObject object = (JSONObject) returnMap.get("data");
			String openid = String.valueOf(object.get("openid")); //公众号的openId
			String access_token = String.valueOf(object.get("access_token"));
			this.getUserInfo(openid,unionid,member); //调用微信更新用户信息
			
		}
	}

	/**
	 * 接受公众号消息
	 * @param map
	 */
	public void acceptPublicMessage(Map<String, String> map) {
		String fromUserName = map.get("FromUserName");
		String toUserName = map.get("ToUserName");
		String msgType = map.get("MsgType");
		String content = map.get("Content");
		String eventType = map.get("Event");
		
		System.out.println("fromUserName："+fromUserName);
		System.out.println("toUserName："+toUserName);
		System.out.println("msgType："+msgType);
		System.out.println("content："+content);
		System.out.println("eventType："+eventType);
		
		String openid=fromUserName;
		boolean insertFlag=true;
		
		EyOfficialAccountsExample example = new EyOfficialAccountsExample();
		com.taotao.pojo.EyOfficialAccountsExample.Criteria criteria = example.createCriteria();
		criteria.andOpenIdEqualTo(openid);
		List<EyOfficialAccounts> list = eyOfficialAccountsMapper.selectByExample(example);
    	EyOfficialAccounts account=new EyOfficialAccounts();
		if(list!=null && list.size()>0){
			account = list.get(0);
			insertFlag=false;
		}
		
		if("subscribe".equals(eventType)){ //关注公众号
			Map<String, Object> tokenMap = this.getAccessTokenGzh(null);
			String accessToken =  (String) tokenMap.get("data");
			String url="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+openid+"&lang=zh_CN";
			System.out.println("获取用户信息参数-->"+url);
	        JSONObject jsonObject = CommonUtil.httpsRequest(url, "GET", "");
	        System.out.println("获取用户信息返回-->"+jsonObject.toJSONString());
	        String errcode = String.valueOf(jsonObject.get("errcode"));
	        if(StringUtils.isNotBlank(errcode) && "40001".equals(errcode)){
	        	RedisUtils.del(WechatServiceImpl.accessToken_gzh_prefix);
	        	this.acceptPublicMessage(map);
	        }
	        
	        
	        this.initOfficialAccounts(jsonObject,account);
	    	account.setCreateTime(DateUtil.getDateAndTime());
	        operateLogService.insert(-1, null,null,openid,OperateType.operateType_29.getCode(),""); 
	        
	    	
			EyMemberExample exampleMember = new EyMemberExample();
			com.taotao.pojo.EyMemberExample.Criteria criteriaMember = exampleMember.createCriteria();
			criteriaMember.andUnionIdEqualTo(account.getUnionId());
			List<EyMember> memberList = eyMemberMapper.selectByExample(exampleMember);
			if(memberList!=null && memberList.size()>0){
				EyMember eyMember = memberList.get(0);
				eyMember.setOpenId2(account.getOpenId());
				eyMemberMapper.updateByPrimaryKey(eyMember);
				
				account.setMemberId(eyMember.getId());
			}
	        
		}else if("unsubscribe".equals(eventType)){ //取消关注公众号
			account.setSubscribe("0");
			operateLogService.insert(-1, null,null,openid,OperateType.operateType_30.getCode(),""); 
		}
	
		if(insertFlag){
			eyOfficialAccountsMapper.insertSelective(account);
		}else{
			eyOfficialAccountsMapper.updateByPrimaryKeySelective(account);
		}
	}


	/**
	 * 获取用户信息
	 * @param openid
	 * @param unionid
	 */
	private EyOfficialAccounts getUserInfo(String openid,String unionid,EyMember member) {
		Map<String, Object> tokenMap = this.getAccessTokenGzh(null);
		String accessToken =  (String) tokenMap.get("data");
		String url="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+openid+"&lang=zh_CN";
		System.out.println("静默授权获取用户信息参数-->"+url);
        JSONObject jsonObject = CommonUtil.httpsRequest(url, "GET", "");
        System.out.println("静默授权获取用户信息返回-->"+jsonObject.toJSONString());
        
        String errcode = String.valueOf(jsonObject.get("errcode"));
        if(StringUtils.isNotBlank(errcode) && "40001".equals(errcode)){
        	RedisUtils.del(WechatServiceImpl.accessToken_gzh_prefix);
        	this.getUserInfo(openid, unionid,member);
        }
        
        EyOfficialAccountsExample example = new EyOfficialAccountsExample();
		com.taotao.pojo.EyOfficialAccountsExample.Criteria criteria = example.createCriteria();
		criteria.andOpenIdEqualTo(openid);
		List<EyOfficialAccounts> list = eyOfficialAccountsMapper.selectByExample(example);
		EyOfficialAccounts account=new EyOfficialAccounts();
		boolean insertFlag=false;
		
		if(list!=null && list.size()>0){
			account = list.get(0);
			this.initOfficialAccounts(jsonObject, account);
		}else{
			this.initOfficialAccounts(jsonObject, account);
			account.setCreateTime(DateUtil.getDateAndTime());
			insertFlag=true;
		}
		
		if(member!=null ){
			account.setMemberId(member.getId());
			member.setOpenId2(openid);
			eyMemberMapper.updateByPrimaryKey(member);
		}
		
		if(insertFlag){
			if("1".equals(account.getSubscribe())){
				eyOfficialAccountsMapper.insertSelective(account);
			}
		}else{
			eyOfficialAccountsMapper.updateByPrimaryKeySelective(account);
		}
		
		operateLogService.insert(member.getId(), null,null,OperateType.operateType_19.getDesc(),OperateType.operateType_19.getCode(),""); 
		
		return account;
	}
	

	private void initOfficialAccounts(JSONObject jsonObject, EyOfficialAccounts account) {
        String country=String.valueOf(jsonObject.get("country"));
        String qr_scene=String.valueOf(jsonObject.get("qr_scene"));
        String subscribe=String.valueOf(jsonObject.get("subscribe"));
        String city=String.valueOf(jsonObject.get("city"));
        String tagid_list=String.valueOf(jsonObject.get("tagid_list"));
        String sex=String.valueOf(jsonObject.get("sex"));
        String groupid=String.valueOf(jsonObject.get("groupid"));
        String language=String.valueOf(jsonObject.get("language"));
        String remark=String.valueOf(jsonObject.get("remark"));
        String subscribe_time=String.valueOf(jsonObject.get("subscribe_time"));
        String province=String.valueOf(jsonObject.get("province"));
        String subscribe_scene=String.valueOf(jsonObject.get("subscribe_scene"));
        String nickname=String.valueOf(jsonObject.get("nickname"));
        String headimgurl=String.valueOf(jsonObject.get("headimgurl"));
        String qr_scene_str=String.valueOf(jsonObject.get("qr_scene_str"));
        String unionid=String.valueOf(jsonObject.get("unionid"));
        String openid=String.valueOf(jsonObject.get("openid"));
     
		account.setSubscribe(subscribe); //是否关注了公众号1是 0否
		if("1".equals(subscribe)){
			if(StringUtils.isNotBlank(subscribe_time)){
	        	Long time = Long.parseLong(subscribe_time);
	        	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
	        	subscribe_time = sdf.format(new Date(time*1000L));
	        }
			account.setOpenId(openid);
			account.setUnionId(unionid);
			account.setCountry(country);
			account.setQrScene(qr_scene);
			account.setCity(city);
			account.setTagidList(tagid_list);
			account.setSex(sex);
			account.setGroupid(groupid);
			account.setLanguage(language);
			account.setRemark(remark);
			account.setSubscribeTime(subscribe_time);
			account.setProvince(province);
			account.setSubscribeScene(subscribe_scene);
			account.setNickname(nickname);
			account.setHeadimgurl(headimgurl);
			account.setQrSceneStr(qr_scene_str);
		}
	
		account.setUpdateTime(DateUtil.getDateAndTime());
	}

	

	public Map<String, Object> sendGet(Map<String, String> map) {
		try {
			String url = map.get("url");
			String params = map.get("params");
			url=url+ "?" + params;
			String sr = HttpRequest.sendGet(url);
			System.out.println("sendGet返回：" + sr);
			JSONObject json = JSONObject.parseObject(sr);

			return baseResult.getSuccMap(json);

		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorMap("sendGet失败");
		}
	}
	
	public Map<String, Object> sendGetLogin(Map<String, String> map) {
		try {
			String url = paramService.getParam("jscode2session_xcx_url");
			String appId_xcx = paramService.getParam("appId_xcx");
			String appSecret_xcx = paramService.getParam("appSecret_xcx");
			String js_code = map.get("js_code");
			String grant_type = map.get("grant_type");
			url=url+ "?" + "appid=" + appId_xcx + "&secret=" + appSecret_xcx + "&js_code=" + js_code+ "&grant_type="+grant_type;
			String sr = HttpRequest.sendGet(url);
			System.out.println("sendGetLogin返回：" + sr);
			JSONObject json = JSONObject.parseObject(sr);

			return baseResult.getSuccMap(json);

		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorMap("sendGet失败");
		}
	}

	/**
	 * 获取公众号的AccessToken
	 */
	public Map<String, Object> getAccessTokenGzh(Map<String, String> map) {
		try {
			String accessToken = RedisUtils.get(WechatServiceImpl.accessToken_gzh_prefix);
			if (StringUtils.isBlank(accessToken)) {
				String appId = paramService.getParam("appId_gzh");
				String appSecret = paramService.getParam("appSecret_gzh");
				String url = "https://api.weixin.qq.com/cgi-bin/token";
				String params = "appid=" + appId + "&secret=" + appSecret + "&grant_type=client_credential";
				System.out.println("获取公众号accessToken请求--->" + url+",param:"+params);
				url=url+ "?" + params;
				String sr = HttpRequest.sendGet(url);
				System.out.println("获取公众号accessToken返回--->" + sr);
				JSONObject json = JSONObject.parseObject(sr);
				String access_token = String.valueOf(json.get("access_token"));
				String expires_in = String.valueOf(json.get("expires_in"));
				RedisUtils.setex(WechatServiceImpl.accessToken_gzh_prefix, Integer.parseInt(expires_in)-1000, access_token);
				return baseResult.getSuccMap(access_token);
			}
			return baseResult.getSuccMap(accessToken);
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorMap("获取AccessToken失败");
		}
	}




	/**
	 * 获取小程序的AccessToken
	 */
	public Map<String, Object> getAccessTokenXcx(Map<String, String> map) {
		try {
			String accessToken = RedisUtils.get(WechatServiceImpl.accessToken_xcx_prefix);
			if (StringUtils.isBlank(accessToken)) {
				String appId = paramService.getParam("appId_xcx");
				String appSecret = paramService.getParam("appSecret_xcx");
				String url = "https://api.weixin.qq.com/cgi-bin/token";
				String params = "appid=" + appId + "&secret=" + appSecret + "&grant_type=client_credential";
				System.out.println("获取小成序accessToken请求--->" + url+",param:"+params);
				url=url+ "?" + params;
				String sr = HttpRequest.sendGet(url);
				System.out.println("获取小程序accessToken返回--->" + sr);
				JSONObject json = JSONObject.parseObject(sr);
				String access_token = String.valueOf(json.get("access_token"));
				String expires_in = String.valueOf(json.get("expires_in"));
				RedisUtils.setex(WechatServiceImpl.accessToken_xcx_prefix, Integer.parseInt(expires_in)-1000, access_token);
				return baseResult.getSuccMap(access_token);
			}
			return baseResult.getSuccMap(accessToken);
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorMap("获取AccessToken失败");
		}
	}
	
	
	public  Map<String, Object>  msgCheck(Map<String, String> map) {
		String secCheck = paramService.getParam("secCheck");
		if("false".equals(secCheck)){  //不校验，返回成功
			return baseResult.getSuccMap();
		}
		
		Map<String, Object> returnMap = this.getAccessTokenXcx(null);
		String accessToken =  (String) returnMap.get("data");
    	String url="https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + accessToken;
    	
    	String content=map.get("content");
    	
    	HashMap<String,String> m=new HashMap<>();
    	m.put("content", content);
		String jsonString = JSON.toJSONString(m);
		
		System.out.println("调用msgCheck请求参数："+jsonString);
		String sendPost = HttpRequest.sendPost(url, jsonString);
		System.out.println("调用msgCheck返回："+sendPost);
		JSONObject object = JSONObject.parseObject(sendPost);
		String errcode=object.get("errcode").toString();
		if ("0".equals(errcode)) {
			return baseResult.getSuccMap();
        }else if("40001".equals(errcode)){ //token失效 删除重试
			RedisUtils.del(WechatServiceImpl.accessToken_xcx_prefix);
			this.msgCheck(map);
		}
		
       	return baseResult.getErrorMap("");
	}
	
	public boolean msgCheck(String msg) {
		if(StringUtils.isBlank(msg)){
			return true;
		}
		String secCheck = paramService.getParam("secCheck");
		if("false".equals(secCheck)){  //不校验，返回成功
			return true;
		}
		
		Map<String, Object> returnMap = this.getAccessTokenXcx(null);
		String accessToken =  (String) returnMap.get("data");
    	String url="https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + accessToken;
    	
    	HashMap<String,String> map=new HashMap<>();
    	map.put("content", msg);
		String jsonString = JSON.toJSONString(map);
    	
		System.out.println("调用msgCheck请求参数："+jsonString);
		String sendPost = HttpRequest.sendPost(url, jsonString);
		System.out.println("调用msgCheck返回："+sendPost);
		JSONObject object = JSONObject.parseObject(sendPost);
		String errcode=object.get("errcode").toString();
		
		if ("0".equals(errcode)) {
			return true;
		}else if("40001".equals(errcode)){ //token失效 删除重试
			RedisUtils.del(WechatServiceImpl.accessToken_xcx_prefix);
			this.msgCheck(msg);
		}
		return false;
		
	}
	
	
	
	public Map<String, Object> decodeData(Map<String, String> map) {
		String encryptedData = map.get("encryptedData");
		String iv = map.get("iv");
		String sessionkey = map.get("sessionkey");
		try {
			System.out.println("decodeData请求参数：" + map.toString());
			String decryptData = DecryptUtil.decrypt(encryptedData, sessionkey, iv);
			System.out.println("decodeData返回：" + decryptData);
			return baseResult.getSuccMap(decryptData);
		} catch (Exception e) {
			logger.error("解密信息失败");
			return baseResult.getErrorMap("解密信息失败");
		}
	}


	/**
	 * 给公众号发送模板消息
	 * @param requestMap
	 * @return
	 */
	public Map<String, Object> sendMsg(Map<String, String> requestMap) {
			String sender=requestMap.get("sender");
			String sessionKey=requestMap.get("sessionKey");
			String messageId=requestMap.get("messageId");
			String receiver=requestMap.get("receiver");
			String content=requestMap.get("content");
			String templateId=requestMap.get("templateId");
			String orderId=requestMap.get("orderId");
			
			EyMember senderMember = eyMemberMapper.selectByPrimaryKey(Integer.parseInt(sender));
			
			EyMember receiverMember = eyMemberMapper.selectByPrimaryKey(Integer.parseInt(receiver));
	
			EyOfficialAccountsExample example = new EyOfficialAccountsExample();
			com.taotao.pojo.EyOfficialAccountsExample.Criteria criteriaPic = example.createCriteria();
			criteriaPic.andUnionIdEqualTo(receiverMember.getUnionId());
			List<EyOfficialAccounts> list = eyOfficialAccountsMapper.selectByExample(example);
			if(list!=null && list.size()>0){
				EyOfficialAccounts accounts = list.get(0);
				Map<String, Object> tokenMap = this.getAccessTokenGzh(null);
				String accessToken =  (String) tokenMap.get("data");
				WxMssVo wx = new WxMssVo();// 发送模板消息请求参数封装对象
				
				Map<String,String> map=new HashMap<String,String>();
				map.put("openId", accounts.getOpenId()); //接受者的openId
				if(templateId.equals(TemplateDesc.Template_1.getCode())){ //客户咨询提醒
					map.put("nickName", senderMember.getNickName()); //发送者昵称
					this.initParamTemplate1(wx,map); 
				}else if(templateId.equals(TemplateDesc.Template_2.getCode())){ //发货提醒通知
					this.initParamTemplate2(wx,map); 
				}else if(templateId.equals(TemplateDesc.Template_3.getCode())){ //购买成功通知
					map.put("nickName", senderMember.getNickName()); //买方昵称
					map.put("orderId",orderId);
					this.initParamTemplate3(wx,map); 
				}else if(templateId.equals(TemplateDesc.Template_4.getCode())){ //订单发货提醒
					this.initParamTemplate4(wx,map); 
				}else if(templateId.equals(TemplateDesc.Template_5.getCode())){ //退款成功通知
					this.initParamTemplate5(wx,map); 
				}
				
				String jsonString = JSON.toJSONString(wx);
				String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
				System.out.println("请求-->:"+jsonString);
			    JSONObject jsonObject = CommonUtil.httpsRequest(url, "POST",jsonString);
				System.out.println("返回-->:"+jsonObject);
				String errcode = String.valueOf(jsonObject.get("errcode"));
				String errmsg=String.valueOf(jsonObject.get("errmsg"));
				if(StringUtils.isNotBlank(errcode) && "40001".equals(errcode)){
			        	RedisUtils.del(WechatServiceImpl.accessToken_gzh_prefix);
			        	this.sendMsg(requestMap);
			        }
				
				String type="2";//公众号模板消息发送
				remindLogService.insert(sessionKey,messageId,sender, String.valueOf(receiverMember.getId()), content, errcode,errmsg,type);
				operateLogService.insert(Integer.parseInt(sender), null,null,"发送公众号模板消息",OperateType.operateType_13.getCode(),sessionKey); 
				
				if(!errcode.equals("0")){//发送失败，可能是用户取消了关注，调用公众号获取用户信息接口重新获取
					this.getUserInfo(accounts.getOpenId(),accounts.getUnionId(),receiverMember); //调用微信更新用户信息
					Map<String, Object> returnMap = sendOfflineMessage(requestMap);
				}
			}else{
				operateLogService.insert(Integer.parseInt(sender), null,null,OperateType.operateType_39.getDesc(),OperateType.operateType_39.getCode(),sessionKey); 
				System.out.println("发送公众号模板消息失败，unionId:"+receiverMember.getUnionId());
			}	
			return baseResult.getSuccMap();
		}
		

		/**
		 * 给公众号发送模板消息 支付成功卖方提醒
		 * @param openid2
		 */

	/**
	 * 给小程序发送订阅消息
	 * @param map
	 * @return
	 */
	@Override
	public Map<String, Object> sendOfflineMessage(Map<String, String> map) {
		try {
			String sender=map.get("sender");
			String receiver=map.get("receiver");
			String sessionKey=map.get("sessionKey");
			String messageId=map.get("messageId");
			String content=map.get("content");
			
			EyMember senderMember = eyMemberMapper.selectByPrimaryKey(Integer.parseInt(sender));
			EyMember receiverMember = eyMemberMapper.selectByPrimaryKey(Integer.parseInt(receiver));
			
			Map<String, Object> returnMap = this.getAccessTokenXcx(null);
			String accessToken =  (String) returnMap.get("data");
			
			String templateId_xcx = paramService.getParam("templateId_xcx");
			
			
	    	WxMssVo wxMssVo = new WxMssVo();
	        wxMssVo.setTouser(receiverMember.getOpenId());//微信推送消息接收者的openid
	        wxMssVo.setTemplate_id(templateId_xcx);//订阅消息模板id
	        wxMssVo.setPage("pages/index/index");

	        Map<String, String> name1 = new HashMap<>();
			Map<String, String> thing3 = new HashMap<>();
			Map<String, String> time4 = new HashMap<>();
			name1.put("value", senderMember.getNickName());
			name1.put("color", "#000000");
			thing3.put("value", "View the message");
			thing3.put("color",  "#000000");
			time4.put("value", DateUtil.getDate2());
			time4.put("color",  "#000000");
			Map<String, Map<String, String>> m = new HashMap<>();
			m.put("name1", name1);
			m.put("thing3", thing3);
			m.put("time4", time4);
			wxMssVo.setData(m);
	    	
			String jsonString = JSON.toJSONString(wxMssVo);

			String url="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;
			String returnString = HttpRequest.sendPost(url, jsonString);
			System.out.println(returnString);
			JSONObject returnJson = JSONObject.parseObject(returnString); 
			String errcode = String.valueOf(returnJson.get("errcode"));
			String errmsg=String.valueOf(returnJson.get("errmsg"));
			
			String type="1";//订阅消息发送
			remindLogService.insert(sessionKey,messageId,sender, receiver, content, errcode,errmsg,type);
			operateLogService.insert(Integer.parseInt(sender), null,null,"发送订阅离线消息",OperateType.operateType_14.getCode(),sessionKey); 
			
			return baseResult.getSuccMap();
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorMap("网络繁忙，请稍后 再试");
		}
	}

	@Override
	public Map<String, Object> querySubscribe(Map<String, String> map) {
		try {
			String memberId=map.get("memberId");
			EyMember member = eyMemberMapper.selectByPrimaryKey(Integer.parseInt(memberId));
			Map<String, String> querySubscribe = commonService.querySubscribe(member.getUnionId());
			return baseResult.getSuccMap(querySubscribe);
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorMap("网络繁忙，请稍后 再试");
		}
	}
	
	
	public void initParamTemplate1(WxMssVo wx,Map<String,String> paramMap) {
		wx.setTouser(paramMap.get("openId").toString()); //接收消息的公众号的openid
		wx.setTemplate_id(TemplateDesc.Template_1.getCode());
		Map<String, String> miniprogram = new HashMap<>();
		String appId = paramService.getParam("appId_xcx");
		miniprogram.put("appid", appId);
		miniprogram.put("pagepath", "pages/message/sessionList/sessionList");
		wx.setMiniprogram(miniprogram);
		Map<String, String> first = new HashMap<>();
		Map<String, String> keyword1 = new HashMap<>();
		Map<String, String> keyword2 = new HashMap<>();
		Map<String, String> keyword3 = new HashMap<>();
		Map<String, String> keyword4 = new HashMap<>();
		Map<String, String> remark = new HashMap<>();
		first.put("value", "Received one message");
		first.put("color", "#808080");
		keyword1.put("value",paramMap.get("nickName").toString());
		keyword1.put("color", "#000000");
		keyword2.put("value", "interest");
		keyword2.put("color", "#000000");
		keyword3.put("value", "easyGoSH");
		keyword3.put("color", "#000000");
		keyword4.put("value", DateUtil.getDate2());
		keyword4.put("color", "#000000");
		remark.put("value", "View the message");
		remark.put("color", "#000000");
		Map<String, Map<String, String>> map = new HashMap<>();
		map.put("first", first);
		map.put("keyword1", keyword1);
		map.put("keyword2", keyword2);
		map.put("keyword3", keyword3);
		map.put("keyword4", keyword4);
		map.put("remark", remark);
		wx.setData(map);
	}
	
	public void initParamTemplate2(WxMssVo wx,Map<String,String> paramMap) {
		
	}
	
	public void initParamTemplate3(WxMssVo wx,Map<String,String> paramMap) {
		String orderId=paramMap.get("orderId").toString();
		
		EyOrder order = eyOrderMapper.selectByPrimaryKey(Integer.parseInt(orderId));
		Integer goodsId = order.getGoodsId();
		EyGoods goods = eyGoodsMapper.selectByPrimaryKey(goodsId);
		EyMember member = eyMemberMapper.selectByPrimaryKey(goods.getMemberId());
		
		wx.setTouser(member.getOpenId2()); //接收消息的公众号的openid
		wx.setTemplate_id(TemplateDesc.Template_3.getCode());
		Map<String, String> miniprogram = new HashMap<>();
		String appId = paramService.getParam("appId_xcx");
		miniprogram.put("appid", appId);
		miniprogram.put("pagepath", "pages/order/sellList/sellList");
		wx.setMiniprogram(miniprogram);
		Map<String, String> first = new HashMap<>();
		Map<String, String> keyword1 = new HashMap<>();
		Map<String, String> keyword2 = new HashMap<>();
		Map<String, String> keyword3 = new HashMap<>();
		Map<String, String> keyword4 = new HashMap<>();
		Map<String, String> keyword5 = new HashMap<>();
		Map<String, String> remark = new HashMap<>();
		first.put("value", "buyers "+paramMap.get("nickName").toString()+" payment success");
		first.put("color", "#808080");
		keyword1.put("value", DateUtil.getDate2());
		keyword1.put("color", "#000000");
		keyword2.put("value", goods.getTitle());
		keyword2.put("color", "#000000");
		keyword3.put("value", order.getPricePay());
		keyword3.put("color", "#000000");
		keyword4.put("value", order.getOutTradeNo());
		keyword4.put("color", "#000000");
		keyword5.put("value", member.getNickName());
		keyword5.put("color", "#000000");
		remark.put("value", "The buyer has paid for one of your orders. Please deliver the goods in time");
		remark.put("color", "#000000");
		Map<String, Map<String, String>> map = new HashMap<>();
		map.put("first", first);
		map.put("keyword1", keyword1);
		map.put("keyword2", keyword2);
		map.put("keyword3", keyword3);
		map.put("keyword4", keyword4);
		map.put("keyword5", keyword5);
		map.put("remark", remark);
		wx.setData(map);
	}
	
	public void initParamTemplate4(WxMssVo wx,Map<String,String> paramMap) {
		
	}
	
	public void initParamTemplate5(WxMssVo wx,Map<String,String> paramMap) {
		
	}


	/**
	 * 获取js
	 */
	public Map<String, Object> getTicket(Map<String, String> map) {
		try {
			String ticket = RedisUtils.get(WechatServiceImpl.ticket);
			if (StringUtils.isBlank(ticket)) {
				Map<String, Object> tokenMap = this.getAccessTokenGzh(null);
				String accessToken =  (String) tokenMap.get("data");
				String ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
				ticketUrl=ticketUrl.replace("ACCESS_TOKEN",accessToken);
				System.out.println("getticket requset-->:" + ticketUrl);
				String sr = HttpRequest.sendGet(ticketUrl);
				System.out.println("getticket response-->:" + sr);
				JSONObject returnJson = JSONObject.parseObject(sr);
				//{"errcode":0,"errmsg":"ok","ticket":"HoagFKDcsGMVCIY2vOjf9tFGUqb46HCECCiHnR6aMW1Ab6I0PkZbRNCiQTmSu921rERy1BdsShOwSxQSIRE6qQ","expires_in":7200}
				if ("0".equals(String.valueOf(returnJson.get("errcode")))) {
					ticket = String.valueOf(returnJson.get("ticket"));
					String expires_in = String.valueOf(returnJson.get("expires_in"));
					RedisUtils.setex(WechatServiceImpl.ticket, Integer.parseInt(expires_in) - 1000, ticket);
				}
			}
			return baseResult.getSuccMap(ticket);
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorMap("获取ticket失败");
		}
	}

	@Override
	public Map<String, Object> getJssdkWechatConfig(Map<String, String> map) {
		Map returnMap= new  HashMap<String, String>();
		try{
			String url=map.get("url");
			Map<String, Object> ticketMap = this.getTicket(null);
			String ticket =  (String) ticketMap.get("data");

			long timestamp=System.currentTimeMillis();
			String nonce_str = UUID.randomUUID().toString();
			// 注意这里参数名必须全部小写，且必须有序
			String  string1 =  "jsapi_ticket="  + ticket +  "&noncestr="  + nonce_str
					+  "&timestamp="  + timestamp  +  "&url="  + url;
			MessageDigest crypt = MessageDigest.getInstance( "SHA-1" );
			crypt.reset();
			crypt.update(string1.getBytes( "UTF-8" ));
			String signature = byteToHex(crypt.digest());

			String appId = paramService.getParam(Constants.appId_gzh);
			returnMap.put( "appId" , appId);
			returnMap.put( "timestamp" , String.valueOf(timestamp));
			returnMap.put( "nonceStr" , nonce_str);
			returnMap.put( "signature" , signature);
		}catch (Exception e){
			e.printStackTrace();
			return baseResult.getErrorMap("获取jssdk配置失败");
		}
		return baseResult.getSuccMap(returnMap);
	}

	private  static  String byteToHex( final  byte [] hash) {
		Formatter formatter =  new  Formatter();
		for  ( byte  b : hash) {
			formatter.format( "%02x" , b);
		}
		String result = formatter.toString();
		formatter.close();
		return  result;
	}

}
